LIBRARY ieee;
USE ieee.std_logic_1164.all;
use ieee.std_logic_unsigned.all;
use ieee.numeric_std.all;

entity sync_driver is
  port (clk : in std_logic;
		rstn : in std_logic;
		hsync : out std_logic;
		vsync : out std_logic;
		next_screen : out std_logic;
		next_line : out std_logic;
		vcounter : out integer);
end entity;

architecture rtl of sync_driver is
  signal hcounter : integer;
  signal i_vcounter : integer;
begin
	process (rstn, clk)
	begin
		if rstn = '0' then
			hcounter <= 0;
			i_vcounter <= 0;
		else
			if rising_edge(clk) then
				if hcounter = 857 then
					if i_vcounter = 523 then
						i_vcounter <= 0;
					else
						i_vcounter <= i_vcounter + 1;
					end if;
					hcounter <= 0;
				else
					hcounter <= hcounter + 1;
				end if;
			end if;
		end if;
	end process;
	
	process (i_vcounter, hcounter)
	begin
		if hcounter = 0 and i_vcounter = 0 then
			vsync <= '0';
		else
			vsync <= '1';
		end if;
	end process;

	process (hcounter)
	begin
		if hcounter = 0 then
			hsync <= '0';
		else
			hsync <= '1';
		end if;
	end process;

	process (i_vcounter, hcounter)
	begin
		if hcounter = 0 and i_vcounter = 42 then
			next_screen <= '1';
		else
			next_screen <= '0';
		end if;
	end process;

	process (hcounter)
	begin
		if hcounter = 0 and i_vcounter mod 2 = 0 then
			next_line <= '1';
		else
			next_line <= '0';
		end if;
	end process;

	vcounter <= i_vcounter;
end rtl;

